package com.social.security;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.social.pojo.Result;
import com.social.pojo.SysMenu;
import com.social.pojo.SysRole;
import com.social.pojo.SysUser;
import com.social.pojo.dto.UserDTO;
import com.social.service.SysMenuService;
import com.social.service.SysRoleService;
import com.social.service.SysUserService;
import com.social.utils.JwtUtils;
import com.social.utils.UserHolder;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.social.constant.RedisConstants.*;

/**
 * 登录成功处理器
 * @author zhm
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        String username = authentication.getName();
        String token = JwtUtils.genJwtToken(username);
        System.out.println("token:  " + token);
        SysUser currentUser = sysUserService.findByUsername(username);
        UserDTO userDTO = BeanUtil.copyProperties(currentUser, UserDTO.class);
        UserHolder.saveUser(userDTO);
        UserDTO user = UserHolder.getUser();
        System.out.println("UserHolder测试：   " + user);
        // 根据用户id获取所有的角色信息
        List<SysRole> roleList = sysRoleService
                .list(new QueryWrapper<SysRole>()
                        .inSql("id", "SELECT role_id FROM sys_user_role WHERE user_id=" + currentUser.getId()));

        // 遍历所有的角色，获取所有菜单权限 而且不重复
        Set<SysMenu> menuSet=new HashSet<>();
        for(SysRole sysRole:roleList){
            List<SysMenu> sysMenuList = sysMenuService
                    .list(new QueryWrapper<SysMenu>()
                            .inSql("id", "SELECT menu_id FROM sys_role_menu WHERE role_id=" + sysRole.getId()));
            for(SysMenu sysMenu:sysMenuList){
                menuSet.add(sysMenu);
            }
        }

        currentUser.setRoles(roleList.stream()
                .map(SysRole::getName)
                .collect(Collectors.joining(",")));

        List<SysMenu> sysMenuList=new ArrayList<>(menuSet);

        // 排序
        sysMenuList
                .sort(Comparator.comparing(SysMenu::getOrderNum));

        // 转菜单树
        List<SysMenu> menuList=sysMenuService
                .buildTreeMenu(sysMenuList);

        Map<String, Object> data = new HashMap<>(2000);
        data.put("authorization",token);
        data.put("currentUser",currentUser);
        data.put("menuList",menuList);
        outputStream.write(JSONUtil.toJsonStr(Result.ok(200, data)).getBytes());
        outputStream.flush();
        outputStream.close();
    }
}
